﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Xml;
using System.IO;
using Clipping.Infrastructure.Models;
using Clipping.Utils;

namespace Settings
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Log4cb.Log4cbHelper logHelper = new Log4cb.Log4cbHelper("Setting");
        private string appDir = AppDomain.CurrentDomain.BaseDirectory;
        private SysSettings sysSettings;
        private UserSettings userSettings;
        private int initTabIndex;
        public MainWindow()
        {
            loadSettings();
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }
        public MainWindow(int tabIndex)
            : this()
        {
            this.initTabIndex = tabIndex;
           }


        private void loadSettings()
        {
            SettingRepository rep = new SettingRepository();
            this.sysSettings = rep.GetSysSettings();
            this.userSettings = rep.GetUserSettings();
            if (sysSettings == null)
                sysSettings = new SysSettings();
            if (userSettings == null)
                userSettings = new UserSettings();
        }

        private void updateUI()
        {
            this.tbx_UserName.Text = this.userSettings.UserName;
            this.tbx_UploadUrl.Text = this.sysSettings.UploadUrl;
            this.tbx_UploadUserName.Text = this.sysSettings.UploadUserName;
            this.pbx_UploadPassword.Password = this.sysSettings.UploadPassword;
            this.tbx_ClientInfoUrl.Text = this.sysSettings.ClientInfoUrl;
            this.tbx_UserInfoUrl.Text = this.sysSettings.UserInfoUrl;
            this.tbx_MediaInfoUrl.Text = this.sysSettings.MediaInfoUrl;
            this.chbx_AutoUpdate.IsChecked = this.sysSettings.AutoUpdate;
            this.chbx_AutoGetContent.IsChecked = this.userSettings.AutoGetContent;
            this.chbx_AutoOpenNews.IsChecked = this.userSettings.AutoOpenNews;
            this.chbx_EmbedPic.IsChecked = this.sysSettings.EmbedPic;
            this.chbx_ZipClipping.IsChecked = this.sysSettings.ZipClipping;
            this.cbx_Encoding.SelectedItem = this.sysSettings.Encoding;

            this.tbx_DefaultAD.Text = this.userSettings.DefaultAD;
            this.tbx_DefaultHeight.Text = this.userSettings.DefaultHeight;
            this.tbx_DefaultWidth.Text = this.userSettings.DefaultWidth;
            this.tbx_DefaultPage.Text = this.userSettings.DefaultPage;
            this.tbx_DefaultPageSize.Text = this.userSettings.DefaultPageSize;
            this.tbx_DefaultWords.Text = this.userSettings.DefaultWords;
            if (this.userSettings.AutoCountWords)
                this.radioBtn_AutoCount.IsChecked = true;
            else
                this.radioBtn_UseDefaultWords.IsChecked = true;

        }

        private void updateSettings()
        {
            this.userSettings.UserName = this.tbx_UserName.Text;
            this.sysSettings.UploadUrl = this.tbx_UploadUrl.Text;
            this.sysSettings.UploadUserName = this.tbx_UploadUserName.Text;
            this.sysSettings.UploadPassword = this.pbx_UploadPassword.Password;
            this.sysSettings.ClientInfoUrl = this.tbx_ClientInfoUrl.Text;
            this.sysSettings.UserInfoUrl = this.tbx_UserInfoUrl.Text;
            this.sysSettings.MediaInfoUrl = this.tbx_MediaInfoUrl.Text;

            if (this.chbx_AutoUpdate.IsChecked.HasValue && this.chbx_AutoUpdate.IsChecked.Value)
                this.sysSettings.AutoUpdate = true;
            else
                this.sysSettings.AutoUpdate = false;
            if (this.chbx_AutoGetContent.IsChecked.HasValue && this.chbx_AutoGetContent.IsChecked.Value)
                this.userSettings.AutoGetContent = true;
            else
                this.userSettings.AutoGetContent = false;
            if (this.chbx_AutoOpenNews.IsChecked.HasValue && this.chbx_AutoOpenNews.IsChecked.Value)
                this.userSettings.AutoOpenNews = true;
            else
                this.userSettings.AutoOpenNews = false;
            if (this.chbx_EmbedPic.IsChecked.HasValue && this.chbx_EmbedPic.IsChecked.Value)
                this.sysSettings.EmbedPic = true;
            else
                this.sysSettings.EmbedPic = false;
            if (this.chbx_ZipClipping.IsChecked.HasValue && this.chbx_ZipClipping.IsChecked.Value)
                this.sysSettings.ZipClipping = true;
            else
                this.sysSettings.ZipClipping = false;
            this.sysSettings.Encoding = this.cbx_Encoding.SelectedItem as string;

            this.userSettings.DefaultAD = this.tbx_DefaultAD.Text;
            this.userSettings.DefaultHeight = this.tbx_DefaultHeight.Text;
            this.userSettings.DefaultWidth = this.tbx_DefaultWidth.Text;
            this.userSettings.DefaultWords = this.tbx_DefaultWords.Text;
            this.userSettings.DefaultPage = this.tbx_DefaultPage.Text;
            this.userSettings.DefaultPageSize = this.tbx_DefaultPageSize.Text;
            if (this.radioBtn_AutoCount.IsChecked == true)
            {
                this.userSettings.AutoCountWords = true;
            }
            else
                this.userSettings.AutoCountWords = false;
                
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.cbx_Encoding.ItemsSource = new List<string> { "UTF-8", "GB2312" };
            updateUI();
            this.tab.SelectedIndex = this.initTabIndex;
        }

        private void btn_Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                updateSettings();
                SettingRepository rep = new SettingRepository();
                rep.SaveSysSettings(this.sysSettings);
                rep.SaveUserSettings(this.userSettings);
                if (App.StartAlone)
                    MessageBox.Show("保存配置成功");
                else
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                logHelper.LogErrMsg(ex, "保存配置");
                MessageBox.Show("保存配置失败");
            }
        }

        private void btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        #region 取客户信息
        private void btn_GetClientInfo_Click(object sender, RoutedEventArgs e)
        {
            if (Uri.IsWellFormedUriString(this.tbx_ClientInfoUrl.Text, UriKind.Absolute))
            {
                this.pb_GetClientInfo.Visibility = System.Windows.Visibility.Visible;
                this.btn_GetClientInfo.IsEnabled = false;
                WebClient wc = new WebClient();
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_ClientInfo_DownloadProgressChanged);
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_ClientInfo_DownloadStringCompleted);
                wc.Encoding = Encoding.UTF8;
                Uri clienturl = new Uri(this.tbx_ClientInfoUrl.Text);
                wc.DownloadStringAsync(clienturl);
            }
            else
            {
                MessageBox.Show("尚未设置用于更新信息的地址，无法执行更新操作！", "无法更新", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        void wc_ClientInfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    string xmlstr = e.Result;
                    ensureDataFolderCreated();
                    File.WriteAllText(System.IO.Path.Combine(appDir, "Data", "ClientInfo.xml"), xmlstr, Encoding.UTF8);
                    MessageBox.Show("更新客户分类信息成功！");
                    this.ClientInfoUpdated = true;
                }
                else
                {
                    this.logHelper.LogErrMsg(e.Error, "更新客户分类信息失败");
                }
            }
            catch (Exception ex)
            {
                this.logHelper.LogErrMsg(ex, "更新客户分类信息失败");
                MessageBox.Show(string.Format("更新客户分类信息失败：{0}{1}", Environment.NewLine, ex.Message), "失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                this.Dispatcher.Invoke((Action)(() => { this.pb_GetClientInfo.Value = 0; this.pb_GetClientInfo.Visibility = System.Windows.Visibility.Collapsed; this.btn_GetClientInfo.IsEnabled = true; }));
            }
        }

        void wc_ClientInfo_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.Dispatcher.Invoke((Action)(() => { this.pb_GetClientInfo.Value = e.ProgressPercentage; }));
        }
        #endregion
        #region 取用户信息
        private void btn_GetUserInfo_Click(object sender, RoutedEventArgs e)
        {
            if (Uri.IsWellFormedUriString(this.tbx_UserInfoUrl.Text, UriKind.Absolute))
            {
                this.pb_GetUserInfo.Visibility = System.Windows.Visibility.Visible;
                this.btn_GetUserInfo.IsEnabled = false;
                WebClient wc_GetUserInfo = new WebClient();
                wc_GetUserInfo.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_GetUserInfo_DownloadProgressChanged);
                wc_GetUserInfo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_GetUserInfo_DownloadStringCompleted);
                wc_GetUserInfo.Encoding = Encoding.UTF8;
                Uri userInfoUrl = new Uri(this.tbx_UserInfoUrl.Text);
                wc_GetUserInfo.DownloadStringAsync(userInfoUrl);
            }
            else
            {
                MessageBox.Show("尚未设置用于更新信息的地址，无法执行更新操作！", "无法更新", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        void wc_GetUserInfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    string xmlstr = e.Result;
                    ensureDataFolderCreated();
                    File.WriteAllText(System.IO.Path.Combine(appDir, "Data", "UserInfo.xml"), xmlstr, Encoding.UTF8);
                    MessageBox.Show("更新用户信息成功！");
                    this.UserInfoUpdated = true;
                }
                else
                {
                    this.logHelper.LogErrMsg(e.Error, "更新用户信息失败");
                }
            }
            catch (Exception ex)
            {
                this.logHelper.LogErrMsg(ex, "更新用户信息失败");
                MessageBox.Show(string.Format("更新用户信息失败：{0}{1}", Environment.NewLine, ex.Message), "失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                this.Dispatcher.Invoke((Action)(() => { this.pb_GetUserInfo.Value = 0; this.pb_GetUserInfo.Visibility = System.Windows.Visibility.Collapsed; this.btn_GetUserInfo.IsEnabled = true; }));
            }
        }

        void wc_GetUserInfo_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.Dispatcher.Invoke((Action)(() => { this.pb_GetUserInfo.Value = e.ProgressPercentage; }));

        }
        #endregion
        #region 取媒体信息
        private void btn_GetMediaInfo_Click(object sender, RoutedEventArgs e)
        {
            if (Uri.IsWellFormedUriString(this.tbx_MediaInfoUrl.Text, UriKind.Absolute))
            {
                this.pb_GetMediaInfo.Visibility = System.Windows.Visibility.Visible;
                this.btn_GetMediaInfo.IsEnabled = false;
                WebClient wc_GetMediaInfo = new WebClient();
                wc_GetMediaInfo.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_GetMediaInfo_DownloadProgressChanged);
                wc_GetMediaInfo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_GetMediaInfo_DownloadStringCompleted);
                wc_GetMediaInfo.Encoding = Encoding.UTF8;
                Uri mediaInfoUrl = new Uri(this.tbx_MediaInfoUrl.Text);
                wc_GetMediaInfo.DownloadStringAsync(mediaInfoUrl);
            }
            else
            {

                MessageBox.Show("尚未设置用于更新信息的地址，无法执行更新操作！", "无法更新", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        void wc_GetMediaInfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    string xmlstr = e.Result;
                    ensureDataFolderCreated();
                    File.WriteAllText(System.IO.Path.Combine(appDir, "Data", "MediaList.xml"), xmlstr, Encoding.UTF8);
                    MessageBox.Show("更新媒体信息成功！");
                    this.MediaInfoUpdated = true;
                }
                else
                {
                    this.logHelper.LogErrMsg(e.Error, "更新媒体信息失败");
                }
            }
            catch (Exception ex)
            {
                this.logHelper.LogErrMsg(ex, "更新媒体信息失败");
                MessageBox.Show(string.Format("更新媒体信息失败：{0}{1}", Environment.NewLine, ex.Message), "失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                this.Dispatcher.Invoke((Action)(() => { this.pb_GetMediaInfo.Value = 0; this.pb_GetMediaInfo.Visibility = System.Windows.Visibility.Collapsed; this.btn_GetMediaInfo.IsEnabled = true; }));
            }
        }

        void wc_GetMediaInfo_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.Dispatcher.Invoke((Action)(() => { this.pb_GetMediaInfo.Value = e.ProgressPercentage; }));

        }

        #endregion

        private void ensureDataFolderCreated()
        {
            var dir = System.IO.Path.Combine(appDir, "Data");
            if (!System.IO.Directory.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);
        }

        public bool ClientInfoUpdated { get; private set; }
        public bool UserInfoUpdated { get; private set; }
        public bool MediaInfoUpdated { get; private set; }
    }
}
